//
//  LLPhotoSelectorViewController.swift
//  01照片选择器UI搭建
//
//  Created by Bingo on 15/11/8.
//  Copyright © 2015年 Bingo. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"

class LLPhotoSelectorViewController: UICollectionViewController {

    
    
    var photos = [UIImage]()
    
    var currentIndexPath: NSIndexPath?
    
    private let maxPhotoCount = 6
    
    private var layout = UICollectionViewFlowLayout()
    
   
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    init(){
        super.init(collectionViewLayout: layout)
    }

    
    override func viewDidLoad() {
        super.viewDidLoad()

        prepareCollectionView()
    }
    
    private func prepareCollectionView(){
        collectionView?.registerClass(LLPhotoSelectorCell.self, forCellWithReuseIdentifier: "cell")
        
        
        collectionView?.backgroundColor = UIColor.whiteColor()
        
        layout.itemSize = CGSize(width: 80, height: 80)
        
        layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
    }
    


//    override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
//        // #warning Incomplete implementation, return the number of sections
//        return 3
//    }


    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        return photos.count < maxPhotoCount ? photos.count + 1 :photos.count
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! LLPhotoSelectorCell
    
        // Configure the cell
        cell.backgroundColor = UIColor.brownColor()
        
        cell.cellDelegate = self
        
        if indexPath.item < photos.count{
            cell.image = photos[indexPath.item]
        }else{
            cell.setAddButton()
        }
        
    
        return cell
    }

}

extension LLPhotoSelectorViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        print("image:\(image)")
        
        let newImage = image.scaleImage()
        
//        let newImage = image.scale
        
        if currentIndexPath?.item < photos.count{
            photos[currentIndexPath!.item] = newImage
        }else{
        
            photos.append(newImage)
        }
    
        collectionView?.reloadData()
        
        picker.dismissViewControllerAnimated(true, completion: nil)
    }

}

extension LLPhotoSelectorViewController:LLPhotoSelectorCellDelegate{

    func LLPhotoSelectorCellAddPhoto(cell:LLPhotoSelectorCell){
    
        if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary){
            print("相册不可用")
            
            return
        }
        
        let picker = UIImagePickerController()
        
        currentIndexPath = collectionView?.indexPathForCell(cell)
        
        picker.delegate = self
        
        presentViewController(picker, animated: true, completion: nil)
    }
    
    func LLPhotoSelectorCellRemovePhoot(cell: LLPhotoSelectorCell) {
        
        let indexPath = collectionView!.indexPathForCell(cell)!
        
        photos.removeAtIndex(indexPath.item)
        
//        collectionView?.reloadData()
        
        if photos.count < 5{
        
            collectionView?.deleteItemsAtIndexPaths([indexPath])
        }else{
            collectionView?.reloadData()
        
        }
        
    }

}

@objc protocol LLPhotoSelectorCellDelegate:NSObjectProtocol{
    
    func LLPhotoSelectorCellAddPhoto(cell:LLPhotoSelectorCell)
    
    func LLPhotoSelectorCellRemovePhoot(cell:LLPhotoSelectorCell)
    
}


class LLPhotoSelectorCell :UICollectionViewCell{

    
    var image:UIImage?{
        
        didSet{
            
            addButton.setImage(image, forState: UIControlState.Normal)
            addButton.setImage(image, forState: UIControlState.Highlighted)
            
            removeButton.hidden = false
            
        }
        
    }
    
    func setAddButton(){
        addButton.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
        addButton.setImage(UIImage(named: "compose_pic_add_highlighted"), forState: UIControlState.Highlighted)
        
        removeButton.hidden = true
    }
    
    //构造函数
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame:CGRect){
        super.init(frame:frame)
        
        prepareUI()
    }
    
    weak var cellDelegate:LLPhotoSelectorCellDelegate?
    
    private func prepareUI(){
        
        contentView.addSubview(addButton)
        contentView.addSubview(removeButton)
        
        addButton.translatesAutoresizingMaskIntoConstraints = false
        removeButton.translatesAutoresizingMaskIntoConstraints = false
        
        let viewDict = ["ad" : addButton , "rb" : removeButton]
        contentView.addConstraints( NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[ad]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDict))
        
    contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[ad]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDict))
        
    contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[rb]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDict))
        
    contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[rb]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDict))
        
    }
    
    //按钮点击事件
    func addButtonClick(){
        
        cellDelegate?.LLPhotoSelectorCellAddPhoto(self)
    }
    
    func removeButtonClick(){
    
        cellDelegate?.LLPhotoSelectorCellRemovePhoot(self)
    }
    
    private lazy var addButton:UIButton = {
    
        let button = UIButton()
        button.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "compose_pic_add_highlighted"), forState: UIControlState.Highlighted)
        
        button.addTarget(self, action: "addButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        button.imageView?.contentMode = UIViewContentMode.ScaleAspectFill
        
        return button
    }()
    
    private lazy var removeButton:UIButton = {
        
        let button = UIButton()
        button.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        
        button.addTarget(self, action: "removeButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        return button
    }()

}
